<template>
  <div class="chat">
    <content-header :title="topic.topic.title" @multi-select="setMultiSelected" @collectTopic="collectTopic" @setTitle="setTitle" @copy-to="copyTo"/>
    <div class="chat-content" ref="chatList">
      <div class="chat-list middle-content">
        <div class="chat-item-wrapper" v-for="qa in topic.topic.qaList" :key="qa.qaId">
          <div class="select-box" v-if="multiSelect">
            <el-checkbox v-model="qa.selected"></el-checkbox>
          </div>
          <ask :message="qa.askMessage"></ask>
          <answer :message="qa.answerMessage" :message-id = "qa.answerMessageId" :qaId = "qa.qaId"></answer>
        </div>
      </div>
    </div>
    <div class="chat-box-wrapper">
      <div class="stop-btn-wrapper">
        <el-button class="stop-chat-btn" v-show="topic.topic.status === TopicStatus.WAITING">
          <el-icon class="stop-icon"></el-icon>
          停止回答
        </el-button>
      </div>
      <div class="chat-box" >
        <div class="chat-input-wrapper">
          <div class="chat-input" contenteditable="true" @input="setNewAsk" @keyup="pressKeyCallback">
            {{newAsk}}
          </div>
        </div>
        <el-button class="send-btn" @click="sendAsk">
          <el-icon><Promotion /></el-icon>
        </el-button>
      </div>
    </div>
    <div class="multi-opt-btn-wrapper" v-if="multiSelect">
      <div class="opt-btn-wrapper flex">
        <div class="share-btn-wrapper btn-wrapper block">
          <el-button class="multi-share-btn opt-btn">
            <el-icon><share-icon></share-icon></el-icon>
          </el-button>
          分享
        </div>
        <div class="copy-btn-wrapper btn-wrapper block">
          <el-button class="multi-copy-btn opt-btn" @click="copyTo">
            <el-icon><copy-icon></copy-icon></el-icon>
          </el-button>
          复制
        </div>
        <div class="delete-btn-wrapper btn-wrapper block">
          <el-button class="multi-delete-btn opt-btn">
            <el-icon><delete-icon></delete-icon></el-icon>
          </el-button>
          删除
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import ContentHeader from "@/components/contentHeader.vue";
import {Promotion} from "@element-plus/icons-vue";
import {onMounted, onUnmounted, ref, type UnwrapRef, watch} from "vue";
import topicStore from "@/stores/topic";
import Ask from "@/components/ask.vue";
import Answer from "@/components/answer.vue";
import visitorStore from "@/stores/visitor";
import {useRoute} from "vue-router";
import {TopicStatus} from "@/constants/TopicStatus";
import collectionStore from "@/stores/collection";
import {setTopicTitle} from "@/apis/api";
import {copy} from "@/utils/helper";
import {ElMessage} from "element-plus";
import ShareIcon from "@/components/icons/shareIcon.vue";
import CopyIcon from "@/components/icons/copyIcon.vue";
import DeleteIcon from "@/components/icons/deleteIcon.vue";
import {channel, socketHeader, socketListener} from "@/apis/socketIO";
import socketStatusStore from "@/stores/SocketStatus";
const topic = topicStore();
const visitor = visitorStore();
const collection = collectionStore();
const newAsk = ref('');
const chatList = ref<Element|null>(null);
const route = useRoute();
const socketStore = socketStatusStore();
const topicId: any = route.query['topic_id'];
topic.topic.topicId = topicId && topicId !== topic.topic.topicId ? topicId : topic.topic.topicId;

const config = { attributes: true, childList: true, subtree: true };

const observer = new MutationObserver(() => {
  scrollToBottom();
});

watch(() => chatList.value, (node) => {
  if(node) {
    observer.observe(node, config);
  }
});
let resize: boolean = false;
const scrollToBottom = () => {
  if(!resize)  {
    resize = true;
    setTimeout(() => {
      const node: UnwrapRef<Element | null> = chatList.value;
      if(node) {
        node.scrollTop = node.scrollHeight;
      }
      resize = false;
    }, 500);
  }

}
scrollToBottom();
const multiSelect = ref(false);
const setNewAsk = (e: any) => {
  if(newAsk.value !== e.target.innerText){
    newAsk.value = e.target.innerText;
  }
}

const  copyTo = () => {
  if(topic.topic && topic.topic.qaList && topic.topic.qaList.length){
    let message:string = '';
    for (const qa of topic.topic.qaList) {
      if(qa.selected || !multiSelect.value ){
        message += ('问： ' + qa.askMessage + '\n\n');
        message += ('答: ' + qa.answerMessage + '\n\n');
      }
    }
    copy(message);
    ElMessage({
      type: 'success',
      message: '复制成功'
    });
  }
  multiSelect.value = false;
}

watch(() => {
  const node = chatList.value as HTMLElement;
 return node;
}, (e) => {
  console.log(e);
})
const  sendAsk = async () => {
  await topic.addQA({
    askMessage: newAsk.value,
    answerMessage: '',
    topicId: topicId,
    askMessageId: '',
    answerMessageId: ''
  });
  newAsk.value = '';
  scrollToBottom();
}
const collectTopic =() => {
  collection.collectTopicMessage(topic.topic.title, <string>topic.topic.topicId, []);
}
const setTitle = async (data:any) => {
  const res = await setTopicTitle(topic.topic.topicId??'', data.title);
  if(res){
    topic.topic.title = data.title;
  }
}
const pressKeyCallback= (e: KeyboardEvent) =>{
  switch (e.key) {
    case 'Enter':
      sendAsk();
      break;
  }
}

const  setMultiSelected = () =>{
  multiSelect.value = !multiSelect.value;
}

socketListener('ReceiveChatMessage', 'chat')((data: any, socket: any, ch: string) => {
  topic.setAnswerMessage(data['answer_message'] ??'', data['qa_id'] ??'');
  topic.topic.status = TopicStatus.RECEIVED;
});

</script>

<style lang="less" scoped>
@import "../assets/common.less";
.chat{
  position: relative;
  height: 100vh;
  .chat-content {
    width: 100%;
    height: 70vh;
    overflow-y: auto;
  }
  .middle-content{
    height: auto;
  }
  .chat-box-wrapper{
    position: absolute;
    //bottom: -24vh;
    margin-bottom: 6vh;
    width: 100%;
    .stop-btn-wrapper{
      width: 100%;
      position: relative;
      display: flex;
      margin-top: 3vh;
      .stop-chat-btn {
        .el-icon{
          background: #3087FF;
          margin-right: 8px;
        }
        color: #3087FF;
        border: 1px #3087FF dashed;
        margin: auto;
        margin-bottom: 8px;
      }
    }
    .chat-box{
      display: flex;
      width: 60%;
      margin: auto;
      height: 10vh;
      box-shadow: 0 0 24px 0 #1d212636;
      border-radius: 8px;
      position: relative;
      .chat-input-wrapper {
        overflow-y: scroll;
        height: 100%;
        width: calc(100% - 10vh);
        .chat-input{
         width: 100%;
          height: 100%;
          padding: 16px;
        }
      }


      .send-btn{
        width: 6vh;
        height: 6vh;
        background: #207BF8;
        border-radius: 8px;
        color: #fff;
        font-size: 3vh;
        position: absolute;
        margin-bottom: 2vh;
        margin-right: 2.3vh;
        margin-top: 2vh;
        right: 0;
      }
    }
  }
}
.topic-chat {
  width: 100% !important;
  .chat-list{
    width: 80% !important;
  }
}
.select-box {
  position: absolute;
  left: -26px;
}

.multi-opt-btn-wrapper{
  position: absolute;
  width: 100%;
  bottom: 0;
  height: 18vh;
  background: #fff;
  padding-top: 16px;
  border-top: 1px solid #b7b7b778;
  .opt-btn-wrapper {
    margin: auto;
    width: 204px;
    .btn-wrapper {
      display: grid;
      margin: 18px;
      .opt-btn {
        border-radius: 100%;
        width: 32px;
        border-color: #36444E;
      }
    }
  }
}
</style>